package org.example.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
@RefreshScope
public class BlackListFilter implements GlobalFilter, Ordered {

    private static Map<String, Integer> callIpMap = new ConcurrentHashMap<>();

    @Value("${gateway.timeInterval}")
    private int timeInterval;
    @Value("${gateway.maxTimes}")
    private int maxTimes;

    private static List<String> blackList = new ArrayList<>();
    private static ScheduledExecutorService executor =
            Executors.newScheduledThreadPool(1);

    @PostConstruct
    private void setSchedule(){
        executor.scheduleAtFixedRate(()->cleanMap(),0,timeInterval, TimeUnit.MINUTES);
    }

    private static void cleanMap(){
        System.out.println("scheduled cleanup");
        callIpMap = new ConcurrentHashMap<>();
    }
    /**
     * 过滤器核心方法
     * @param exchange 封装了request和response对象的上下文
     * @param chain 网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("gateway.timeInterval="+timeInterval);
        System.out.println("gateway.maxTimes="+maxTimes);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String clientIp = request.getRemoteAddress().getHostString();
        if(blackList.contains(clientIp)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("=====>IP:" + clientIp + " 在黑名单中，将被拒绝访问！");
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            response.setStatusCode(HttpStatus.valueOf(303));
            return response.writeWith(Mono.just(wrap));
        }

        // 防暴暴刷控制
        if(!callIpMap.containsKey(clientIp)){
            callIpMap.put(clientIp, 1);
        } else {
            callIpMap.put(clientIp, callIpMap.get(clientIp)+1);
        }
        if(callIpMap.get(clientIp)>maxTimes){
            blackList.add(clientIp);
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("=====>IP:" + clientIp + " 被加入黑名单中，将被拒绝访问！");
            String data = "您频繁进⾏行行注册，请求已被拒绝!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            response.setStatusCode(HttpStatus.valueOf(303));
            return response.writeWith(Mono.just(wrap));
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
